package cn.myjerry.io.others;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 文件 --> 程序 --> 字节数组
 * 
 * 
 * 字节数组 --> 程序 --> 文件
 * @author Jerry
 *
 */

public class ByteArrayDemo02 {
	public static void main(String[] args) throws IOException {
		byte[] data = getBytesFromFile("/Users/zpon/Desktop/test.txt");
		//System.out.println(new String(data));
		toFileFromByteArray(data, "/Users/zpon/Desktop/test01.txt");
	}
	/**
	 * 字节数组 --> 程序 --> 文件
	 * @throws IOException 
	 */
	public static void toFileFromByteArray(byte[] src, String destPath) throws IOException {
		// 创建源
		// 目的地
		File dest = new File(destPath);
		// 选择流
		BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(src));
		BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dest, true));
		
		byte[] flush = new byte[1024];
		int len = 0;
		while(-1 != (len = is.read(flush))) {
			os.write(flush, 0, len);
		}
		os.flush();
		os.close();
		is.close();
	}
	
	/**
	 * 文件 --> 程序 --> 字节数组
	 * @param srcPath
	 * @return
	 * @throws IOException
	 */
	public static byte[] getBytesFromFile(String srcPath) throws IOException {
		// 创建文件源
		File src = new File(srcPath);
		// 创建字节数组目的地
		byte[] best = null;
		
		// 选择流
		InputStream is = new BufferedInputStream(new FileInputStream(src));
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		
		byte[] flush = new byte[1024];
		int len = 0;
		
		while(-1 != (len=is.read(flush))) {
			bos.write(flush, 0, len);
		}
		best = bos.toByteArray();
		bos.flush();
		bos.close();
		is.close();
		return best;
	}
}
